import { Form, Input, Button, Table, Popconfirm, Space, Select, Pagination } from 'antd'
import { useNavigate } from 'react-router-dom';
import './articlePublish.scss'
import { useEffect, useState } from 'react';
import ArticleDetail from './ArticleDetail/ArticleDetail';
import http from '../../utils/http'
import store from '../../store';

const { Option } = Select;
const Article_publishing_management = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm();
  const [isArticleDetail, setDetail] = useState(false);
  const [data, setData] = useState([])  //表格数据
  const [value1, setValue1] = useState()
  const [delkey, setDelkey] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  //渲染数据表格、搜索 
  function publishData() {
    http({
      url: '/article/findArticle',
      params: {
        artTitle: form.getFieldsValue().username ? form.getFieldsValue().username : '',
        artType: form.getFieldsValue().type ? form.getFieldsValue().type : '',
      }
    }).then((res) => {
      console.log('渲染文章发布管理表格', res);
      store.lijuhua.total = res.data.countRows;
      if (res.code == 200) {
        let arr = res.data.listArticle.map((v, i) => {
          return {
            key: v.artId,
            title: v.artTitle,
            avenues: v.artChannel,
            channel: v.artDitch,
            type: v.artType,
            keyword: v.artKeyWord,
            publisher: v.adminId,
            sendtime: v.artSendTime
          }
        })
        setData(arr)
      }
    })
  }

  // 渲染文章发布表格
  useEffect(() => {
    publishData();
  }, [])

  // 搜索
  const search = () => {
    // console.log(form.getFieldsValue().type);
    publishData();
    // pageChange();
  }

  // 重置
  const resize = () => {
    setSelectedRowKeys([]);
    store.lijuhua.current = 1
    form.setFieldsValue({
      username: '',
      type: ''
    })
    publishData();
  }

  // 页码
  const pageChange = (page, size) => {
    store.lijuhua.current = page
    http({
      url: '/article/findArticle',
      params: {
        current: page,
      }
    }).then((res) => {
      console.log('渲染文章发布管理表格', res);
      if (res.code == 200) {
        console.log(res.data.listArticle);
        let arr = res.data.listArticle.map((v, i) => {
          return {
            key: v.artId,
            title: v.artTitle,
            avenues: v.artChannel,
            channel: v.artDitch,
            type: v.artType,
            keyword: v.artKeyWord,
            publisher: v.adminId,
            sendtime: v.artSendTime
          }
        })
        setData(arr)
      }
    })
  }

  // 跳转到新增页面
  const add = () => {
    navigate('/home/Operate/ArticleAdd')
  }

  // 跳转到详情组件，将点击的该行key值传到详情页面
  const openEditBox = (text, record) => {
    // console.log(text,record);
    setDetail(true)
    setValue1(record.key)
    // store.lijuhua.setA(record.content)
  }

  // 取消删除操作
  function cancel(e) {
    console.log('cancel', e);
  }
  // 确认删除操作
  function confirm(text, record) {
    let id = [];
    if (record) {
      // 单删
      id.push(record.key)
    } else {
      // 批量删除
      id = delkey;
    }
    console.log(id);
    http({
      url: '/article/deleteArticle',
      method: 'post',
      data: id
    }).then((res) => {
      console.log(res);
      publishData();
    })
  }

  // 表头
  const columns = [
    {
      title: '文章标题',
      dataIndex: 'title',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '发布渠道',
      dataIndex: 'avenues',
    },
    {
      title: '发布频道',
      dataIndex: 'channel',
    },
    {
      title: '文章类型',
      dataIndex: 'type',
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
    },
    {
      title: '发布人',
      dataIndex: 'publisher',
    },
    {
      title: '发送时间',
      dataIndex: 'sendtime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => { openEditBox(text, record) }}>详情</a>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => { confirm(text, record) }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 前端data假数据
  // const data = [
  //   {
  //     key: '1',
  //     title: '对于年龄，你焦虑了吗？',
  //     avenues: '小程序',
  //     channel: '今日热点',
  //     type: '图文',
  //     keyword: '年龄',
  //     publisher: '管理员',
  //     sendtime: '2022-1-23'
  //   },
  //   {
  //     key: '2',
  //     title: '对于年龄，你焦虑了吗？',
  //     avenues: '小程序',
  //     channel: '今日热点',
  //     type: '图文',
  //     keyword: '年龄',
  //     publisher: '管理员',
  //     sendtime: '2022-1-23'
  //   },
  //   {
  //     key: '3',
  //     title: '对于年龄，你焦虑了吗？',
  //     avenues: '小程序',
  //     channel: '今日热点',
  //     type: '图文',
  //     keyword: '年龄',
  //     publisher: '管理员',
  //     sendtime: '2022-1-23'
  //   }
  // ]; // rowSelection object indicates the need for row selection

  const rowSelection = {
    // 选中每行的数据，相当于scope
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
      setDelkey(selectedRowKeys);
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record) => ({
      key: record.key,
    }),
  };

  if (isArticleDetail) {
    return <div>
      <ArticleDetail value1={value1} setDetail={setDetail} />
    </div>
  } else {
    return <div className='roleContent'>
      <Form form={form} name="horizontal_login" layout="inline" className='title'>
        <Form.Item
          name="username">
          <div className='kuai'>
            <span></span>
            <span>文章发布管理</span>
          </div>
        </Form.Item>
        <Form.Item className='btn'>
          <div>
            <Button className='cha'
              type="primary"
              onClick={add}>新增</Button>
            <Popconfirm title='确定要将它们全部删除吗？'
              onConfirm={() => { confirm() }}
              onCancel={cancel} okText='YES' cancelText='NO'>
              <a href='#'> <Button className='resize' type="primary">批量删除</Button></a>
            </Popconfirm>
          </div>
        </Form.Item>
      </Form>
      <div className='biao'>
        <Form form={form} name="horizontal_login" layout="inline" className='Role'>
          <Form.Item
            name="username"
            label='文章标题'
          ><Input placeholder='请输入文章标题' />
          </Form.Item>
          <Form.Item
            name="type"
            label='文章类型'
          >
            <Select placeholder='请选择' className='select'>
              <Option value="图文">图文</Option>
              <Option value="视频">视频</Option>
            </Select>
          </Form.Item>
          <Form.Item className='btn'>
            <div>
              <Button className='cha'
                type="primary"
                onClick={search}>查询</Button>
              <Button className='resize' onClick={resize} type="primary">重置</Button>
            </div>

          </Form.Item>
        </Form>
        <Table className='table1' pagination={false}
          rowSelection={{
            ...rowSelection,
          }}
          columns={columns}
          dataSource={data}

        />
        <Pagination className='page' defaultCurrent={1} current={store.lijuhua.current} total={store.lijuhua.total} onChange={pageChange} />
      </div>
    </div>
  }

};

export default Article_publishing_management;
